package com.rc.evcharger.service.rc;

import com.rc.evcharger.common.constant.level.UserLevelConstant;
import com.rc.evcharger.component.UidGenerator;
import com.rc.evcharger.mapper.member.MemberAccountMapper;
import com.rc.evcharger.mapper.member.MemberAccountRecordMapper;
import com.rc.evcharger.mapper.member.MemberInfoMapper;
import com.rc.evcharger.mapper.order.OrderDiscountRecordMapper;
import com.rc.evcharger.mapper.rc.*;
import com.rc.evcharger.model.member.MemberAccount;
import com.rc.evcharger.model.member.MemberAccountRecord;
import com.rc.evcharger.model.member.MemberInfo;
import com.rc.evcharger.model.order.OrderDiscountRecord;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.model.rc.*;
import com.rc.evcharger.vo.cost.UserLevelPriceResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: yang
 * @Date: 2022/7/5 22:39
 */
@Service
public class RcMemberGainSettingRecordServiceImpl implements RcMemberGainSettingRecordService {

    @Autowired
    private RcMemberGainSettingRecordMapper rcMemberGainSettingRecordMapper;

    @Autowired
    private RcMemberFlagMapper rcMemberFlagMapper;

    @Autowired
    private RcMemberGainGradeSettingMapper rcMemberGainGradeSettingMapper;

    @Autowired
    private MemberAccountRecordMapper memberAccountRecordMapper;

    @Autowired
    private RcMemberLevelSettingMapper rcMemberLevelSettingMapper;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private RcMemberGainGradeRecordMapper rcMemberGainGradeRecordMapper;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Autowired
    private OrderDiscountRecordMapper orderDiscountRecordMapper;

    @Autowired
    private RcMemberGainSettingMapper rcMemberGainSettingMapper;

    @Autowired
    private UidGenerator uidGenerator;

    @Override
    public RcMemberGainSettingRecordMapper getMapper() {
        return rcMemberGainSettingRecordMapper;
    }


    @Override
    public UserLevelPriceResult updateOrderInfo(OrderInfo orderInfo) {
        if (orderInfo.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return UserLevelPriceResult.emptyResult();
        }

        UserLevelPriceResult userLevelPriceResult = UserLevelPriceResult.emptyResult();
        List<OrderDiscountRecord> orderDiscountRecords = new ArrayList<>();

        RcMemberFlag rcMemberFlag = rcMemberFlagMapper.selectByPrimaryKey(orderInfo.getMemberId());
        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(orderInfo.getMemberId());
        MemberAccount memberAccount = memberAccountMapper.selectByPrimaryKey(orderInfo.getMemberId());

        if ("0".equals(rcMemberFlag.getIsMemberLevel())) {
            return UserLevelPriceResult.emptyResult();
        }

        if("1".equals(rcMemberFlag.getGiveStatus())){
            return UserLevelPriceResult.emptyResult();
        }

        //添加优惠记录
        OrderDiscountRecord orderDiscount = new OrderDiscountRecord();
        orderDiscount.setTenantCode(orderInfo.getTenantCode());
        orderDiscount.setOrderId(orderInfo.getOrderId());
        orderDiscount.setCreatedTime(new Date());
        orderDiscount.setDiscountNum(uidGenerator.genDiscountOrderNum("Y"));

//        MemberAccountRecord memberAccountRecord = memberAccountRecordMapper.selectRechargeRecord(memberAccount.getMemberId());
//        if (memberAccountRecord == null) {
//            return UserLevelPriceResult.emptyResult();
//        }

        //TODO 充值消费折扣
        RcMemberLevelSetting rcMemberLevelSetting = rcMemberLevelSettingMapper.selectByMemberSubLevel(rcMemberFlag.getSubLevel());
        if (rcMemberLevelSetting != null) {
            //计算优惠金额
            BigDecimal discountAmountPart = orderInfo.getPayAmount().subtract(orderInfo.getPayAmount().multiply(rcMemberLevelSetting.getDiscountAmount()).setScale(2, BigDecimal.ROUND_HALF_UP));
            orderInfo.setPayAmount(orderInfo.getPayAmount().subtract(discountAmountPart));
            orderInfo.setDiscountAmount(orderInfo.getDiscountAmount().add(discountAmountPart));
            orderInfo.setLevelDiscount(rcMemberLevelSetting.getDiscountAmount().multiply(BigDecimal.TEN)); //会员折扣

//            orderDiscount.setDiscountId(null);
            orderDiscount.setDiscountAmount(discountAmountPart);
            orderDiscount.setDiscountName("充值消费折扣");
            orderDiscount.setDiscountType(UserLevelConstant.RC_RECHARGE_DISCOUNT + "");
            orderDiscountRecords.add(orderDiscount);
        }

        //权益金计费
        OrderDiscountRecord orderDiscountRecord = updateOrderInfoByGiveAmount(orderInfo, memberAccount);
        if (orderDiscountRecord != null) {
            orderDiscountRecords.add(orderDiscountRecord);
        }
        userLevelPriceResult.setOrderDiscountRecords(orderDiscountRecords);


        return userLevelPriceResult;
    }

    @Override
    public OrderDiscountRecord updateOrderInfoByGiveAmount(OrderInfo orderInfo, MemberAccount memberAccount) {
        if (orderInfo.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }
        if (memberAccount.getGiveAccount().compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }

        //默认不享受权益金
        if ("0".equals(orderInfo.getIsUseGiveAmount())) {
            return null;
        }

        //添加优惠记录
        OrderDiscountRecord orderDiscount = new OrderDiscountRecord();
        orderDiscount.setTenantCode(orderInfo.getTenantCode());
        orderDiscount.setOrderId(orderInfo.getOrderId());
        orderDiscount.setDiscountId(memberAccount.getMemberId());
        orderDiscount.setDiscountNum(uidGenerator.genDiscountOrderNum("Q"));
        orderDiscount.setCreatedTime(new Date());

        BigDecimal result = orderInfo.getPayAmount().subtract(memberAccount.getGiveAccount());
        if (result.compareTo(BigDecimal.ZERO) >= 0) {

            orderDiscount.setDiscountAmount(memberAccount.getGiveAccount());
            orderDiscount.setDiscountName("权益金");
            orderDiscount.setDiscountType(UserLevelConstant.RC_GIVE_AMOUNT_DISCOUNT + "");
            orderDiscountRecordMapper.insertSelective(orderDiscount);

            orderInfo.setPayAmount(result);
            orderInfo.setDiscountAmount(orderInfo.getDiscountAmount().add(memberAccount.getGiveAccount()));
            orderInfo.setGiveAmount(memberAccount.getGiveAccount());
            memberAccount.setGiveAccount(BigDecimal.ZERO);

//            memberAccountMapper.updateByPrimaryKeySelective(memberAccount);
        } else {

            orderDiscount.setDiscountAmount(orderInfo.getPayAmount());
            orderDiscount.setDiscountName("权益金");
            orderDiscount.setDiscountType(UserLevelConstant.RC_GIVE_AMOUNT_DISCOUNT + "");
            orderDiscountRecordMapper.insertSelective(orderDiscount);

            memberAccount.setGiveAccount(memberAccount.getGiveAccount().subtract(orderInfo.getPayAmount()));
//            memberAccountMapper.updateByPrimaryKeySelective(memberAccount);

            orderInfo.setDiscountAmount(orderInfo.getDiscountAmount().add(orderInfo.getPayAmount()));
            orderInfo.setPayAmount(BigDecimal.ZERO);
            orderInfo.setGiveAmount(orderInfo.getPayAmount()); //权益金
        }
        return orderDiscount;
    }

    /**
     * 解冻权益金
     *
     * @param orderInfo
     * @param memberAccount
     * @return
     */
    @Override
    public int updateGiveAccount(OrderInfo orderInfo, MemberAccount memberAccount) {
        if (orderInfo.getPayAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return 0;
        }
        if (memberAccount.getFrozenGiveAccount().compareTo(BigDecimal.ZERO) <= 0) {
            return 0;
        }

        //会员权益与相关内容是否冻结
        RcMemberFlag rcMemberFlag = rcMemberFlagMapper.selectByPrimaryKey(memberAccount.getMemberId());
        if ("1".equals(rcMemberFlag.getGiveStatus())){
            return 0;
        }


        //查找最新权益金
        MemberAccountRecord memberAccountRecord = memberAccountRecordMapper.selectGiveAmountType(orderInfo.getMemberId(), "2", null);
        if (memberAccountRecord == null) {
            return 0;
        }

        //查找对应充值记录
        MemberAccountRecord memberAccountRecord0 = memberAccountRecordMapper.selectGiveAmountType(orderInfo.getMemberId(), "0", memberAccountRecord.getLocalTradeNo());
        if (memberAccountRecord0 != null) {
            BigDecimal hisAccount = memberAccountRecord0.getResult().subtract(memberAccountRecord0.getAmount());
            if (hisAccount.compareTo(memberAccount.getAccount()) >= 0) {
                //冻结金额大于赠送金额 否则按冻结金额赠送
                if (memberAccount.getFrozenGiveAccount().compareTo(memberAccountRecord.getAmount()) >= 0) {
                    memberAccount.setGiveAccount(memberAccount.getGiveAccount().add(memberAccountRecord.getAmount()));
                    memberAccount.setFrozenGiveAccount(memberAccount.getFrozenGiveAccount().subtract(memberAccountRecord.getAmount()));
                } else {
                    memberAccount.setGiveAccount(memberAccount.getGiveAccount().add(memberAccount.getFrozenGiveAccount()));
                }
            }

            memberAccountRecord.setFrozenStatus("1");//解冻
            memberAccountRecord.setLastUpdatedTime(new Date());
            memberAccountRecordMapper.updateByPrimaryKeySelective(memberAccountRecord);

        }

        return 0;
    }
}
